<template>
  <!-- 作业管理 -->
  <!-- <bread-crumb />
  <x-card :width="98" :height="1050" style="margin: 20px 20px" message=""> -->
  <!-- 搜索及操作区域 -->
  <x-search>
    <template #search>
      <a-input
        v-model:value="searchTitle"
        placeholder="作业标题"
        style="width: 150px"
      />
      <a-select
        v-model:value="class_id"
        placeholder="查询班级"
        style="width: 120px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in all_classes"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select
        v-model:value="program_id"
        placeholder="查询专业"
        style="width: 120px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in all_programs"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select
        v-model:value="level_id"
        placeholder="作业等级"
        style="width: 120px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in gradeList"
          :key="index"
          :value="item"
        >
          {{ item }}
        </a-select-option>
      </a-select>
      <!-- <a-select
        v-model:value="currentHomework.teacher"
        mode="tags"
        style="width: 150px"
        placeholder="请选择作业布置老师"
        :options="teacher_list"
      ></a-select> -->
      <a-select
        v-model:value="seach_teacher"
        show-search
        placeholder="请选择作业布置老师"
        style="width: 180px; margin-left: 10px"
        :options="teacher_list"
        :filter-option="filterOption"
      ></a-select>
      <!-- <a-date-picker
        v-model:value="exam_date"
        placeholder="布置日期"
        style="width: 150px; margin-left: 10px"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      /> -->
      <a-range-picker
        v-model:value="exam_date"
        show-time
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        :placeholder="['作业布置开始时间', '作业布置结束时间']"
        style="width: 300px; margin-left: 10px"
      />
      <a-button type="primary" style="margin-left: 10px" @click="search_data">
        搜索
      </a-button>
      <a-button style="margin-left: 10px" @click="resetSearch"> 重置 </a-button>
    </template>

    <template #operate>
      <a-button
        type="primary"
        @click="showAddDrawer"
        style="margin-right: 10px"
        v-checkpermission:foo.bar="'homework_search_add'"
      >
        <template #icon><plus-outlined style="margin-right: 0" /></template>
        新建作业
      </a-button>
      <a-button style="background: #67c23a; color: #ffffff; width: 80px">
        <template #icon>
          <DownloadOutlined style="margin-right: 0" />
        </template>
        导出
      </a-button>
    </template>
  </x-search>

  <!-- 数据表格 -->
  <a-table
    :dataSource="tableData"
    :columns="columns"
    :pagination="pagination"
    :loading="loading"
    bordered
    style="margin-top: 20px"
    @change="handleTableChange"
    :scroll="{ x: 1300, y: 600 }"
    v-checkpermission:foo.bar="'homework_search_list'"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'difficulty'">
        <a-tag v-if="record.difficulty === '困难'" color="#f50"> 困难 </a-tag>
        <a-tag v-if="record.difficulty === '中等'" color="#108ee9">
          中等
        </a-tag>
        <a-tag v-if="record.difficulty === '简单'" color="#87d068">
          简单
        </a-tag>
      </template>
      <template v-if="column.dataIndex === 'action'">
        <a-space>
          <!-- 预览图片按钮 -->
          <a-tooltip title="预览图片" placement="top">
            <a-button
              type="text"
              size="small"
              @click="showPhoto(record)"
              v-checkpermission:foo.bar="'homework_search_list'"
            >
              <template #icon>
                <PictureOutlined style="color: #91959c" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 作业详情按钮 -->
          <a-tooltip title="作业详情" placement="top">
            <a-button
              type="text"
              size="small"
              @click="work_detail(record)"
              v-checkpermission:foo.bar="'homework_search_list'"
            >
              <template #icon>
                <FileTextOutlined style="color: #91959c" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 批改详情按钮 -->
          <a-tooltip title="作业批改详情" placement="top">
            <a-button
              type="text"
              size="small"
              @click="corrent_detail(record)"
              v-checkpermission:foo.bar="'homework_search_list'"
            >
              <template #icon>
                <EyeOutlined style="color: #91959c" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 编辑按钮 -->
          <a-tooltip title="编辑" placement="top">
            <a-button
              type="text"
              size="small"
              @click="showEdit(record)"
              v-checkpermission:foo.bar="'homework_search_edit'"
            >
              <template #icon>
                <EditOutlined style="color: #52c41a" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 上传图片按钮 -->
          <a-tooltip title="上传图片" placement="top">
            <a-button
              type="text"
              size="small"
              @click="uploadimg(record)"
              v-checkpermission:foo.bar="'homework_search_edit'"
            >
              <template #icon>
                <UploadOutlined style="color: #722ed1" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 状态切换按钮 -->
          <a-tooltip
            :title="record.state_del === 0 ? '禁用' : '启用'"
            placement="top"
          >
            <a-button
              type="text"
              size="small"
              :danger="record.state_del === 0"
              @click="
                record.state_del === 0
                  ? confirmnot(record)
                  : confirmstart(record)
              "
              v-checkpermission:foo.bar="'homework_search_delete'"
            >
              <template #icon>
                <DeleteOutlined
                  :style="{
                    color: record.state_del === 0 ? '#ff4d4f' : '#52c41a',
                  }"
                />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 真删除按钮 -->
          <a-tooltip v-if="record.state_del === 1" title="删除" placement="top">
            <a-button
              type="text"
              size="small"
              danger
              @click="confirmDelete(record)"
              v-checkpermission:foo.bar="'homework_search_delete'"
            >
              <template #icon>
                <DeleteOutlined style="color: #cf1322" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 批改按钮 -->
          <a-tooltip title="批改" placement="top">
            <a-button
              type="text"
              size="small"
              @click="gradeAssignment(record)"
              v-checkpermission:foo.bar="'homework_search_set'"
            >
              <template #icon>
                <FormOutlined style="color: #fa8c16" />
              </template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>
    </template>
  </a-table>

  <!-- 新增/编辑抽屉 -->
  <a-drawer
    v-model:open="drawerVisible"
    :title="currentAction === 'add' ? '新建作业' : '编辑作业'"
    width="500"
  >
    <a-form
      :model="currentHomework"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="作业标题" required>
        <a-input
          v-model:value="currentHomework.title"
          placeholder="请输入作业标题"
        />
      </a-form-item>
      <a-form-item label="所属班级" required>
        <a-select
          v-model:value="currentHomework.class_id"
          placeholder="请选择班级"
        >
          <a-select-option
            v-for="(item, index) in all_classes"
            :key="index"
            :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="作业描述">
        <a-textarea
          v-model:value="currentHomework.description"
          :rows="4"
          placeholder="请输入作业描述"
        />
      </a-form-item>
      <a-form-item label="布置日期" required>
        <a-date-picker
          v-model:value="currentHomework.set_date"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="截止日期" required>
        <a-date-picker
          v-model:value="currentHomework.due_date"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="作业难度">
        <a-select
          v-model:value="currentHomework.difficulty"
          placeholder="请选择作业难度"
        >
          <a-select-option
            v-for="(item, index) in gradeList"
            :key="index"
            :value="item"
          >
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="布置老师" required>
        <!-- <a-input
          v-model:value="currentHomework.teacher"
          placeholder="请输入作业布置老师"
        /> -->
        <a-select
          v-model:value="currentHomework.teacher"
          show-search
          style="width: 100%"
          placeholder="请选择作业布置老师"
          :options="teacher_list"
          :filter-option="filterOption"
        ></a-select>
      </a-form-item>
      <a-form-item label="作业图片" required>
        <div v-if="currentAction === 'add'">
          <a-upload
            name="file"
            :action="uploadUrl"
            :headers="headers"
            @change="(info:any) => handleUploadChange(info, 'addOredit')"
            :data="UploadData"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              点击上传
            </a-button>
          </a-upload>
          <p style="color: #ccc; font-size: 12px">
            注：一个作业只能存在一张图片
          </p>
        </div>
        <div v-else>
          <div v-if="picture_name !== '暂未设置图片'">
            <a-upload
              name="file"
              :action="uploadUrl"
              :headers="headers"
              @change="(info:any) => handleUploadChange(info, 'addOredit')"
              :data="UploadData"
            >
              <a-button>
                <upload-outlined></upload-outlined>
                点击上传
              </a-button>
            </a-upload>
            <a-image :width="200" :src="picture" />
            <p style="color: #ff4d4f; font-size: 12px">此作业已设置图片</p>
            <p style="color: #ccc; font-size: 12px">
              注：一个作业只能存在一张图片
            </p>
          </div>
          <div v-else>
            <a-upload
              name="file"
              :action="uploadUrl"
              :headers="headers"
              @change="(info:any) => handleUploadChange(info, 'addOredit')"
              :data="UploadData"
            >
              <a-button>
                <upload-outlined></upload-outlined>
                点击上传
              </a-button>
            </a-upload>
            <p style="color: #ff4d4f; font-size: 12px">此作业未设置图片</p>
            <p style="color: #ccc; font-size: 12px">
              注：一个作业只能存在一张图片
            </p>
          </div>
        </div>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="drawerVisible = false">取消</a-button>
        <a-button type="primary" @click="submitForm">提交</a-button>
      </a-space>
    </template>
  </a-drawer>

  <!-- 上传图片的Modal -->
  <a-modal
    v-model:visible="open_upload"
    title="上传图片"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-upload
      name="file"
      :action="uploadUrl"
      :headers="headers"
      @change="handleUploadChange"
      :data="UploadData"
    >
      <a-button>
        <upload-outlined></upload-outlined>
        点击上传
      </a-button>
    </a-upload>
  </a-modal>

  <!-- 预览图片的Modal -->
  <a-modal
    v-model:visible="open_view"
    title="作业图片预览"
    @ok="handleOk"
    :centered="true"
    style="text-align: center"
  >
    <div
      v-if="picture_name === '暂未设置图片'"
      style="margin: 150px auto; text-align: center"
    >
      暂无图片
    </div>
    <div v-else style="margin: auto; text-align: center">
      <a-image
        :width="200"
        :src="picture"
        :preview="{
          src: picture,
          width: '60%',
          height: 'auto',
        }"
      />
    </div>
    <!-- {{ picture }} -->
    <!-- <img :src="picture" alt="" style="width: 200px;"/> -->
  </a-modal>

  <!-- 作业批改的Model -->
  <a-modal
    v-model:visible="open_correct"
    title="作业批改"
    @ok="handleOk_c"
    style="text-align: center"
    width="900px"
  >
    <x-search>
      <template #search>
        <a-input
          v-model:value="searchName_c"
          placeholder="学生名字"
          style="width: 150px"
        />
        <a-button type="primary" style="margin-left: 10px" @click="all_student">
          查询
        </a-button>
        <a-button style="margin-left: 10px" @click="resetSearch_c">
          重置
        </a-button>
      </template>
    </x-search>
    <a-table
      :dataSource="tableData_c"
      :columns="columns_c"
      :loading="loading_c"
      :pagination="pagination_c"
      bordered
      style="margin-top: 20px"
      @change="handleTableChange_c"
      :scroll="{ y: 800 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'status'">
          <a-select v-model:value="record.status" placeholder="选择状态">
            <a-select-option
              v-for="(item, index) in all_status"
              :key="index"
              :value="item"
            >
              {{ item }}
            </a-select-option>
          </a-select>
        </template>
        <template v-if="column.dataIndex === 'score'">
          <a-input-number
            id="inputNumber"
            v-model:value="record.score"
            :min="0"
            :max="100"
          />
        </template>
        <template v-if="column.dataIndex === 'comment'">
          <a-textarea
            placeholder="请输入评语"
            v-model:value="record.comment"
            show-count
            :maxlength="100"
          />
          <!-- <a-input v-model:value="record.comment" /> -->
        </template>
        <template v-if="column.dataIndex === 'action'">
          <a-tooltip title="保存批改">
            <a-button
              type="text"
              @click="saveCorrect(record)"
              style="padding: 0 4px"
            >
              <template #icon>
                <EditOutlined />
              </template>
              保存
            </a-button>
          </a-tooltip>

          <a-tooltip title="重置批改">
            <a-button
              type="text"
              @click="resetCorrect(record)"
              style="padding: 0 4px; color: #fa8c16"
            >
              <template #icon>
                <FormOutlined />
              </template>
              重置
            </a-button>
          </a-tooltip>
        </template>
      </template>
    </a-table>
  </a-modal>

  <!-- 作业详情 -->
  <a-drawer
    title="作业详情"
    :width="720"
    :visible="previewVisible"
    :body-style="{ paddingBottom: '80px' }"
    @close="onClose"
  >
    <a-descriptions bordered :column="1">
      <!-- 基础信息 -->
      <a-descriptions-item label="作业ID">{{
        detailData.id
      }}</a-descriptions-item>
      <a-descriptions-item label="作业标题">
        <span class="detail-title">{{ detailData.title }}</span>
      </a-descriptions-item>
      <a-descriptions-item label="课程信息">
        {{ detailData.class_name }} (ID: {{ detailData.class_id }})
      </a-descriptions-item>
      <a-descriptions-item label="专业">{{
        detailData.program_name
      }}</a-descriptions-item>

      <!-- 教师信息 -->
      <a-descriptions-item label="布置教师">
        {{ detailData.teacherName }} (ID: {{ detailData.teacher_id }})
      </a-descriptions-item>

      <!-- 时间信息 -->
      <a-descriptions-item label="布置日期">
        <a-tag color="blue">{{ detailData.set_date }}</a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="截止日期">
        <a-tag :color="getDueDateTagColor(detailData.due_date)">
          {{ detailData.due_date }}
        </a-tag>
      </a-descriptions-item>

      <!-- 难度 -->
      <a-descriptions-item label="难度">
        <a-tag :color="getDifficultyColor(detailData.difficulty)">
          {{ detailData.difficulty }}
        </a-tag>
      </a-descriptions-item>

      <!-- 作业描述 -->
      <a-descriptions-item label="作业描述">
        <div class="detail-description">
          {{ detailData.description || "暂无描述" }}
        </div>
      </a-descriptions-item>

      <!-- 作业图片 -->
      <a-descriptions-item label="作业图片" v-if="detailData.picture">
        <a-image :width="300" :src="getFullImageUrl(detailData.picture)" />
      </a-descriptions-item>
    </a-descriptions>
  </a-drawer>

  <!-- 作业批改详情 -->
  <a-modal
    v-model:visible="open_correct_view"
    title="作业批改"
    @ok="handleOk_c"
    style="text-align: center"
    width="900px"
  >
    <x-search>
      <template #search>
        <a-input
          v-model:value="searchName_c"
          placeholder="学生名字"
          style="width: 150px"
        />
        <a-button type="primary" style="margin-left: 10px" @click="all_student">
          查询
        </a-button>
        <a-button style="margin-left: 10px" @click="resetSearch_c">
          重置
        </a-button>
      </template>
    </x-search>
    <a-table
      :dataSource="tableData_c"
      :columns="columns_view"
      :pagination="pagination_c"
      :loading="loading_view"
      bordered
      style="margin-top: 20px"
      @change="handleTableChange_c"
      :scroll="{ y: 800 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ record.status }}
          </a-tag>
        </template>
        <template v-if="column.dataIndex === 'score'">
          <a-tag :color="getScoreColor(record.score)">
            {{ record.score }}
          </a-tag>
        </template>
        <template v-if="column.dataIndex === 'comment'">
          <a-tag v-if="!record.comment" color="error"> 暂未评语 </a-tag>
        </template>
      </template>
    </a-table>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  EditOutlined, // 编辑图标
  UploadOutlined, // 上传图标
  EyeOutlined, // 预览图标
  DeleteOutlined, // 删除图标
  FormOutlined, // 批改图标
  PlusOutlined,
  DownloadOutlined,
  PictureOutlined,
  FileTextOutlined,
} from "@ant-design/icons-vue";
import dayjs from "dayjs";
import http from "../routerutils/http";
import XSearch from "./XSearch.vue";
import { useStore } from "vuex";
const store = useStore();
const userPermiss_vuex = store.state.userPermiss;
// 创建一个自定义指令，来统一处理权限存在与否
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      // 移除元素
      el.parentNode?.removeChild(el);
    }
    console.log(el, binding);
    // el.classList.add("is-highlight");
  },
};

// 类型定义
interface ClassInfo {
  id?: string;
  name: string;
}

interface Homework {
  id?: number;
  title: string;
  description: string;
  class_name?: string;
  teacherName?: string;
  set_date?: string;
  due_date?: string;
  difficulty: string;
  teacher?: undefined;
  picture?: string;
  class_id?: number;
}

/* 新区：老师列表 */
const seach_teacher = ref();
const teacher_list = ref<object[]>([]);
const get_teacher = async () => {
  try {
    const res = await http.get("/api/users/teacher_list");
    if (res.data.code === 0) {
      teacher_list.value = res.data.results.map((item: any) => {
        return {
          value: item.id,
          label: item.truename,
        };
      });
    }
  } catch (error) {
    console.log("出错了：：:", error);
  }
};
// 老师搜索
const filterOption = (input: string, option: any) => {
  console.log("筛选：：", option);
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

/* 区一：搜索相关知识 */
// 搜索相关
const searchTitle = ref<string>();
const class_id = ref<string>();
const program_id = ref<string>();
const level_id = ref<string>();
const exam_date = ref<object[]>([]);

// 搜索按钮
const search_data = () => {
  pagination.current = 1;
  pagination.pageSize = 10;
  console.log(pagination.current);
  loadData();
};

// 初始化数据
onMounted(() => {
  loadData();
  get_teacher();
  loadClasses();
  loadPrograms();
  loadStudent();
});

// 加载作业等级数据
const gradeList = ref<string[]>(["简单", "中等", "困难"]);
const all_classes = ref<ClassInfo[]>([]);
const all_programs = ref<ClassInfo[]>([]);
const all_studentList = ref<ClassInfo[]>([]);

// 加载班级数据
const loadClasses = async () => {
  try {
    const res = await http.get("/api/students/allclass");
    all_classes.value = res.data.results;
  } catch (error) {
    message.error("班级数据加载失败");
  }
};

// 加载专业数据
const loadPrograms = async () => {
  try {
    const res = await http.get("/api/students/allprogram");
    all_programs.value = res.data.results;
  } catch (error) {
    message.error("专业数据加载失败");
  }
};

// 加载学生数据
const loadStudent = async () => {
  try {
    const res = await http.get("/api/attends/allStudent");
    all_studentList.value = res.data.results;
  } catch (error) {
    message.error("专业数据加载失败-学生");
  }
};

// 重置搜索

const resetSearch = () => {
  seach_teacher.value = undefined;
  searchTitle.value = undefined;
  class_id.value = undefined;
  program_id.value = undefined;
  level_id.value = undefined;
  exam_date.value = [];
  loadData();
};

// 批改-充值
const resetSearch_c = () => {
  searchName_c.value = ''
  all_student()
}

/* 区二：表格系列 */
// 数据列表
const tableData = ref<Homework[]>([]);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ["10", "20", "50"],
  showTotal: (total: number) => `共 ${total} 条`, // 显示总条数
});
const loading = ref(false); // 表格的加载

// 表格列配置--表头
const columns = reactive([
  {
    title: "作业ID",
    dataIndex: "id",
    width: 80,
    fixed: "left",
  },
  {
    title: "作业标题",
    dataIndex: "title",
    width: 200,
    fixed: "left",
  },
  {
    title: "作业描述",
    dataIndex: "description",
    width: 300,
    ellipsis: true, // 启用文本省略
  },
  {
    title: "布置日期",
    dataIndex: "set_date",
    width: 150,
  },
  {
    title: "截止日期",
    dataIndex: "due_date",
    width: 150,
  },
  {
    title: "班级",
    dataIndex: "class_name",
    width: 150,
  },
  {
    title: "专业",
    dataIndex: "program_name",
    width: 150,
  },
  {
    title: "难度等级",
    dataIndex: "difficulty",
    width: 120,
  },
  {
    title: "布置教师",
    dataIndex: "teacherName",
    width: 120,
    ellipsis: true, // 启用文本省略
  },
  {
    title: "作业图片地址",
    dataIndex: "picture",
    width: 260,
  },
  {
    title: "操作",
    dataIndex: "action",
    width: 280,
    fixed: "right",
  },
]);

// 加载作业数据
const loadData = async () => {
  try {
    loading.value = true;
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      title: searchTitle.value?.trim(),
      class_id: class_id.value,
      teacher_id: seach_teacher.value,
      program_id: program_id.value,
      difficulty: level_id.value,
      // set_date: exam_date.value,
      // set_date_start, set_date_end,
      set_date_start: exam_date.value[0]
        ? dayjs(exam_date.value[0]).format("YYYY-MM-DD HH:mm:ss")
        : null,
      set_date_end: exam_date.value[1]
        ? dayjs(exam_date.value[1]).format("YYYY-MM-DD HH:mm:ss")
        : null,
    };

    const res = await http.get("/api/assignments/list", { params });
    tableData.value = res.data.results.assignments;
    pagination.total = res.data.results.total[0].count;
    console.log(res.data.results.total[0].count);
  } catch (error) {
    message.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

/* 区三：操作系列 */
// 表单相关
const drawerVisible = ref(false);
const currentAction = ref<"add" | "edit">("add");
const currentHomework = reactive<Homework>({
  title: "",
  description: "",
  difficulty: "中等",
  teacher: undefined,
});
// 显示新增抽屉
const showAddDrawer = () => {
  //  title, description, class_id, set_date, due_date, difficulty, teacher
  currentAction.value = "add";
  Object.assign(currentHomework, {
    id: undefined,
    title: "",
    description: "",
    class_id: undefined,
    set_date: undefined,
    due_date: undefined,
    difficulty: undefined,
    teacher: "",
    picture: "",
  });
  drawerVisible.value = true;
};

// 显示编辑抽屉
const showEdit = (record: Homework) => {
  console.log(record);
  currentAction.value = "edit";
  Object.assign(currentHomework, {
    id: record.id,
    title: record.title,
    description: record.description,
    class_name: record.class_name,
    class_id: record.class_id,
    difficulty: record.difficulty,
    teacher: record.teacherName,
    set_date: record.set_date,
    due_date: record.due_date,
    picture: record.picture,
  });
  drawerVisible.value = true;
  picture_name.value = record.picture;
  picture.value = `${baseUrl}/${record.picture}`;
};

// 提交表单--提交后端
const submitForm = async () => {
  if (!validateForm()) return;

  try {
    const payload = { ...currentHomework };
    if (currentAction.value === "add") {
      await http.post("/api/assignments/add", payload);
      message.success("创建成功");
    } else {
      await http.post(`/api/assignments/set`, payload);
      message.success("更新成功");
    }
    drawerVisible.value = false;
    loadData();
  } catch (error) {
    message.error("操作失败");
  }
};

// 表单验证
const validateForm = () => {
  if (!currentHomework.title?.trim()) {
    message.warning("请输入作业标题");
    return false;
  }
  if (!currentHomework.class_id) {
    message.warning("请选择所属班级");
    return false;
  }
  if (!currentHomework.difficulty) {
    message.warning("请选择作业难度");
    return false;
  }
  if (!currentHomework.set_date) {
    message.warning("请选择布置日期");
    return false;
  }
  if (!currentHomework.due_date) {
    message.warning("请选择截止日期");
    return false;
  }
  if (dayjs(currentHomework.due_date).isBefore(currentHomework.set_date)) {
    message.warning("截止日期不能早于布置日期");
    return false;
  }
  return true;
};

// 禁用确认
const confirmnot = (record: Homework) => {
  Modal.confirm({
    title: "禁用作业",
    content: "您确定要禁用此作业吗？",
    centered: true,
    async onOk() {
      try {
        const res = await http.get(`/api/assignments/del_f`, {
          params: {
            id: record.id,
          },
        });
        if (res.data.code === 0) {
          message.success(res.data.msg);
          loadData();
        } else {
          message.error(res.data.msg);
        }
        // message.success("删除成功");
      } catch (error) {
        message.error("删除失败");
      }
    },
  });
};
// 启用
const confirmstart = (record: Homework) => {
  Modal.confirm({
    title: "启用作业",
    content: "您确定要启用此作业吗？",
    centered: true,
    async onOk() {
      try {
        const res = await http.get(`/api/assignments/start`, {
          params: {
            id: record.id,
          },
        });
        if (res.data.code === 0) {
          message.success(res.data.msg);
          loadData();
        } else {
          message.error(res.data.msg);
        }
      } catch (error) {
        message.error("删除失败");
      }
    },
  });
};
// 删除
const confirmDelete = (record: Homework) => {
  Modal.confirm({
    title: "删除作业",
    content: "您确定要删除此作业吗？",
    centered: true,
    async onOk() {
      try {
        const res = await http.get(`/api/assignments/del_t`, {
          params: {
            id: record.id,
          },
        });
        if (res.data.code === 0) {
          message.success(res.data.msg);
          loadData();
        } else {
          message.error(res.data.msg);
        }
      } catch (error) {
        message.error("删除失败");
      }
    },
  });
};

// uploadimg上传图片按钮
const open_upload = ref(false);
const uploadUrl = "/api/assignments/upload"; // 你的上传接口
const token = localStorage.getItem("token");
const headers = {
  authorization: `Bear ${token}`, // 如果需要认证，可以在这里添加token
};
const UploadData = ref({
  id: "",
});
const uploadimg = (record: any) => {
  open_upload.value = true;
  let UploadId = record.id;
  UploadData.value = { id: UploadId }; // 更新 uploadData 的值
  console.log(UploadData.value);
};
const handleOk = () => {
  open_upload.value = false;
  open_view.value = false;
};

const handleCancel = () => {
  open_upload.value = false;
  open_view.value = false;
};

const handleUploadChange = (info: any, type: string) => {
  if (info.file.status === "done") {
    message.success(`${info.file.name} 上传成功`);
    if (type === "addOredit") {
      currentHomework.picture = info.file.response.data.fileName;
    }
    console.log(info.file.response.data.fileName);
    loadData();
  } else if (info.file.status === "error") {
    message.error(`${info.file.name} 上传失败`);
  }
};

// 图片预览
const open_view = ref<boolean>(false);
const baseUrl = "http://localhost:3000"; // 你的服务器地址
const picture_name = ref();
const picture = ref<string>("");
const showPhoto = (record: any) => {
  open_view.value = true;
  picture_name.value = record.picture;
  picture.value = `${baseUrl}/${record.picture}`;
  console.log(picture.value);
};

// 详情显示（需根据实际需求实现）
const work_detail = async (record: Homework) => {
  try {
    const res = await http.get("/api/assignments/get", {
      params: {
        id: record.id,
      },
    });
    if (res.data.code === 0) {
      console.log("数据获取成功：：", res.data);
      previewVisible.value = true;
      detailData.value = res.data.results[0];
    }
  } catch (error) {
    console.log("报错了：：", error);
  }
};

// 创建响应式变量存储作业详情
const detailData = ref({
  class_id: 0,
  class_name: "",
  description: "",
  difficulty: "",
  due_date: "",
  id: 0,
  picture: "",
  program_name: "",
  set_date: "",
  state_del: 0,
  teacherName: "",
  teacher_id: 0,
  title: "",
});
const previewVisible = ref(false);

// 获取完整图片URL（根据实际项目调整）
const getFullImageUrl = (path: any) => {
  if (!path) return "";
  // 这里根据你的实际项目URL结构调整
  return path.startsWith("http") ? path : `http://localhost:3000/${path}`;
};

// 关闭
const onClose = () => {
  previewVisible.value = false;
};

// 根据难度获取标签颜色
const getDifficultyColor = (difficulty: any) => {
  const colors = {
    简单: "green",
    中等: "orange",
    困难: "red",
  };
  return colors[difficulty] || "blue";
};

// 根据截止日期获取标签颜色
const getDueDateTagColor = (dueDate: any) => {
  if (!dueDate) return "default";

  const today = new Date();
  const due = new Date(dueDate);

  if (due < today) return "red"; // 已过期
  if (due - today < 86400000 * 3) return "orange"; // 3天内到期
  return "green"; // 未到期
};

// 批改作业（需根据实际需求实现）
interface tableData_c_rule {
  id: number;
  name: string;
  student_id: number;
  status: string; // 无提交记录时显示默认状态
  score: number;
  comment: string;
}
// 1. 定义需要的响应数据
const open_correct = ref<boolean>(false);
const open_correct_view = ref<boolean>(false);
const searchName_c = ref<string>("");
const homework_id = ref<number>();
const work_class_id = ref<number>();
const tableData_c = ref<tableData_c_rule[]>([]);
const pagination_c = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ["10", "20", "50"],
  showTotal: (total: number) => `共 ${total} 条`, // 显示总条数
});
// let currentCorrect = reactive({
//   status: "",
//   score: 0,
//   comment: ""
// });
const all_status = reactive(["完成", "未完成", "迟交"]);
const columns_c = reactive([
  {
    title: "学生姓名",
    dataIndex: "name",
    width: 100,
    fixed: "left",
  },
  {
    title: "学生学号",
    dataIndex: "student_id",
    width: 100,
  },
  {
    title: "完成状态",
    dataIndex: "status",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "score",
    width: 120,
  },
  {
    title: "评语",
    dataIndex: "comment",
    width: 280,
  },
  {
    title: "操作",
    dataIndex: "action",
    width: 180,
    fixed: "right",
  },
]);
const columns_view = reactive([
  {
    title: "学生姓名",
    dataIndex: "name",
    width: 100,
    fixed: "left",
  },
  {
    title: "学生学号",
    dataIndex: "student_id",
    width: 180,
  },
  {
    title: "完成状态",
    dataIndex: "status",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "score",
    width: 120,
  },
  {
    title: "评语",
    dataIndex: "comment",
    width: 280,
  },
]);
const loading_c = ref(false);
const loading_view = ref(false);
// 样式映射
const getStatusColor = (status: string) => {
  const statusColors = {
    未批改: "red",
    完成: "green",
    未完成: "red",
    迟交: "orange",
  };
  return statusColors[status] || "default";
};
const getScoreColor = (score: number) => {
  if (score > 90) return "green";
  if (score > 80) return "blue";
  if (score > 60) return "orange";
  return "red";
};
// 2. 根据班级的id去寻找这个班级的全部学生
const all_student = async () => {
  try {
    loading_c.value = true;
    loading_view.value = true;
    const res = await http.get("/api/assignments/student_list", {
      params: {
        // 关键点：使用 params 字段传递 GET 参数
        id: homework_id.value,
        class_id: work_class_id.value,
        name: searchName_c.value.trim(),
        page_size: pagination_c.pageSize,
        page: pagination_c.current,
      },
    });
    pagination_c.total = res.data.results.total;
    tableData_c.value = res.data.results.students;
    console.log("请求成功：", res, res.data);
    // 初始化表单数据
    //   currentCorrect = tableData_c.value.map(item => ({
    //   status: item.status,
    //   score: item.score,
    //   comment: item.comment
    // }));
  } catch (error: any) {
    console.log("请求失败", error);
  } finally {
    loading_c.value = false;
    loading_view.value = false;
  }
};
// 3. 批改的按钮
const gradeAssignment = (record: Homework) => {
  message.info(`进入批改页面 - ${record.title}`);
  open_correct.value = true;
  work_class_id.value = record.class_id;
  homework_id.value = record.id;
  all_student();
};
// 查看详情
const corrent_detail = (record: Homework) => {
  open_correct_view.value = true;
  work_class_id.value = record.class_id;
  homework_id.value = record.id;
  all_student();
};

const handleOk_c = () => {
  open_correct.value = false;
};
// 4. 批改表格中的操作
// 保存批改
const saveCorrect = async (record: any) => {
  console.log(record);
  const submitted_at = dayjs().format("YYYY-MM-DD HH:mm:ss");
  console.log(submitted_at);
  try {
    // 2024-09-20 12:00:00,当前时间
    const submitted_at = dayjs().format("YYYY-MM-DD HH:mm:ss");
    // assignment_id, student_id, status, submitted_at, score, comment
    const res = await http.post("/api/assignments/correct", {
      assignment_id: homework_id.value,
      student_id: record.id,
      status: record.status,
      submitted_at: submitted_at,
      score: record.score,
      comment: record.comment,
    });
    if (res.data.results.affectedRows) {
      console.log("批改成功：", res);
      message.success(`${record.name}的作业已批改`);
    }
    console.log(res);
  } catch (error: any) {
    console.log("保存批改请求失败", error);
  }
};
// 重置已批改
const resetCorrect = (record: any) => {
  record.status = "未完成";
  record.score = 0;
  record.comment = "";
};
// 分页处理
const handleTableChange_c = (pag: any) => {
  pagination_c.current = pag.current;
  pagination_c.pageSize = pag.pageSize;
  loadData();
};

/*
作业批改详情
*/
</script>

<style>
.ant-tag {
  margin: 0;
  min-width: 60px;
  text-align: center;
}
:deep([data-v-4579cfca] .anticon) {
  margin-right: 0px;
}
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
:deep(.ant-image-preview-img){
  max-width: 60% !important;
}

:where(.css-dev-only-do-not-override-1p3hq3p).ant-image-preview-root .ant-image-preview-img {
    max-width: 60% !important;
    max-height: 60% !important;
    vertical-align: middle;
    transform: scale3d(1, 1, 1);
    cursor: grab;
    transition: transform 0.3s cubic-bezier(0.215, 0.61, 0.355, 1) 0s;
    user-select: none;
    pointer-events: auto;
}
/* :deep(.anticon) {
  margin-right: 0px;
} */
</style>